package com.qunar.flight.myserver;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.text.SimpleDateFormat;
import java.util.Date;

public class RequestHandler implements Handler {
	private SocketChannel sc;

	RequestHandler(SocketChannel sc) {
		this.sc = sc;
	}

	public void handle() throws IOException {
		System.out.print(getClass());
		ByteBuffer requestBB = ByteBuffer.allocate(1024 * 4);
		sc.read(requestBB);
		String rbb=new String(requestBB.array()).trim();
		if(rbb.indexOf("favicon.ico")>-1)return;//�ܾ���ܴ�����������
		System.out.println("�����ַ�Ϊ��" + rbb);
		File fn = new File("E:\\workspace0\\nioSamples\\test.txt");
		FileChannel fc = new RandomAccessFile(fn, "r").getChannel();
		long length = fc.size();
		int tag=(int)(Math.random()*10);
		System.out.println(tag+"��ʼ�������ļ��r���"+new SimpleDateFormat("HH:mm:ss").format(new Date()));
		try {
			Thread.currentThread().sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		fc.transferTo(0, length, sc);		
		System.out.println(tag+"�������������"+new SimpleDateFormat("HH:mm:ss").format(new Date()));
		sc.close();
		if (fc != null) {
			fc.close();
			fc=null;
		}
	}

	public void run() {
		try {
			handle();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
